package com.aracky.assess.controller;

import com.aracky.assess.model.entity.HrKpiFile;
import com.aracky.assess.service.HrKpiFileService;
import com.aracky.common.config.FastDFSClientWrapper;
import com.aracky.common.util.FileUtil;
import com.aracky.common.vo.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 绩效考核文件表 前端控制器
 * </p>
 *
 * @author zzp
 * @since 2022-08-26 09:28:05
 */
@RestController
@RequestMapping("/hrKpiFile")
@Api(tags = "绩效考核文件相关接口")
public class HrKpiFileController {

    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;

    @Autowired
    private HrKpiFileService hrKpiFileService;

    @SneakyThrows
    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "MultipartFile"),
            @ApiImplicitParam(name = "businessId", value = "业务id", required = false, dataType = "long"),
    })
    @Transactional(rollbackFor = Exception.class)
    public CommonResult upload(@RequestParam("file") MultipartFile file,
                               @RequestParam("businessId") Long businessId) {
        String originalFileName = file.getOriginalFilename();
        String extension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        String path = fastDFSClientWrapper.uploadFile(file.getBytes(), file.getSize(), extension);

        //保存文件信息
        HrKpiFile hrKpiFile = new HrKpiFile();
        hrKpiFile.setFileName(originalFileName);
        hrKpiFile.setFilePath(path);
        hrKpiFile.setBusinessId(businessId);
        hrKpiFileService.save(hrKpiFile);
        return CommonResult.success(hrKpiFile.getFileId(), "文件上传成功");
    }


    @SneakyThrows
    @GetMapping("/download")
    @ApiOperation(value = "文件下载")
    @ApiImplicitParam(name = "fileId", value = "文件id", dataType = "long")
    public ResponseEntity<byte[]> download(Long fileId) {
        //先查询文件信息
        HrKpiFile kpiFile = hrKpiFileService.getById(fileId);
        if (kpiFile == null) {
            return null;
        }
        String path = kpiFile.getFilePath();
        String fileName = kpiFile.getFileName();
        return FileUtil.downloadFile(fileName, fastDFSClientWrapper.downloadFile(path));
    }

}
